// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [2025-07-29]
// (c) 2020-2025 ALYR.NET
// ================================================

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const chalk = require('chalk');

/**
 * 智能多语言依赖自动安装器
 * @class SmartInstaller
 * @description 自动检测项目中的编程语言并安装相应依赖
 */
class SmartInstaller {
  constructor() {
    this.supportedLanguages = {
        "Node.js": {
                "files": [
                        "package.json"
                ],
                "commands": [
                        "npm install",
                        "yarn install"
                ],
                "check": "npm --version"
        },
        "Python": {
                "files": [
                        "requirements.txt",
                        "pyproject.toml",
                        "setup.py",
                        "Pipfile"
                ],
                "commands": [
                        "pip install -r requirements.txt",
                        "pipenv install",
                        "poetry install"
                ],
                "check": "python --version"
        },
        "Java": {
                "files": [
                        "pom.xml",
                        "build.gradle",
                        "build.gradle.kts"
                ],
                "commands": [
                        "mvn install",
                        "gradle build",
                        "./gradlew build"
                ],
                "check": "java -version"
        },
        "Go": {
                "files": [
                        "go.mod",
                        "go.sum"
                ],
                "commands": [
                        "go mod download",
                        "go mod tidy"
                ],
                "check": "go version"
        },
        "Rust": {
                "files": [
                        "Cargo.toml",
                        "Cargo.lock"
                ],
                "commands": [
                        "cargo build",
                        "cargo fetch"
                ],
                "check": "cargo --version"
        },
        "PHP": {
                "files": [
                        "composer.json",
                        "composer.lock"
                ],
                "commands": [
                        "composer install",
                        "composer update"
                ],
                "check": "php --version"
        },
        "Ruby": {
                "files": [
                        "Gemfile",
                        "Gemfile.lock"
                ],
                "commands": [
                        "bundle install",
                        "gem install"
                ],
                "check": "ruby --version"
        },
        "C#": {
                "files": [
                        "*.csproj",
                        "*.sln",
                        "packages.config"
                ],
                "commands": [
                        "dotnet restore",
                        "nuget restore"
                ],
                "check": "dotnet --version"
        },
        "Flutter": {
                "files": [
                        "pubspec.yaml",
                        "pubspec.lock"
                ],
                "commands": [
                        "flutter pub get",
                        "dart pub get"
                ],
                "check": "flutter --version"
        },
        "Swift": {
                "files": [
                        "Package.swift",
                        "Podfile"
                ],
                "commands": [
                        "swift package resolve",
                        "pod install"
                ],
                "check": "swift --version"
        }
};
    
    this.detectedProjects = [];
    this.installResults = [];
  }

  /**
   * 扫描项目目录，检测所有编程语言
   * @param {string} rootPath - 项目根目录
   */
  async scanProject(rootPath = path.resolve(__dirname, '../..')) {
    console.log(chalk.blue('🔍 开始扫描项目目录...'));
    console.log(chalk.gray(`扫描路径: ${rootPath}`));
    
    this.detectedProjects = [];
    
    // 递归扫描目录
    await this.scanDirectory(rootPath, 0, 3); // 最大深度3层
    
    if (this.detectedProjects.length === 0) {
      console.log(chalk.yellow('⚠️  未检测到任何支持的项目类型'));
      return false;
    }
    
    console.log(chalk.green(`✅ 检测完成，发现 ${this.detectedProjects.length} 个项目:`));
    this.detectedProjects.forEach((project, index) => {
      console.log(chalk.cyan(`  ${index + 1}. ${project.language} - ${project.path}`));
      console.log(chalk.gray(`     配置文件: ${project.configFiles.join(', ')}`));
    });
    
    return true;
  }

  /**
   * 递归扫描目录
   * @param {string} dirPath - 目录路径
   * @param {number} currentDepth - 当前深度
   * @param {number} maxDepth - 最大深度
   */
  async scanDirectory(dirPath, currentDepth, maxDepth) {
    if (currentDepth > maxDepth) return;
    
    try {
      const items = fs.readdirSync(dirPath);
      
      // 检查当前目录是否包含项目配置文件
      for (const [language, config] of Object.entries(this.supportedLanguages)) {
        const foundFiles = [];
        
        for (const pattern of config.files) {
          if (pattern.includes('*')) {
            // 处理通配符模式
            const regex = new RegExp(pattern.replace('*', '.*'));
            const matches = items.filter(item => regex.test(item));
            foundFiles.push(...matches);
          } else {
            // 精确匹配
            if (items.includes(pattern)) {
              foundFiles.push(pattern);
            }
          }
        }
        
        if (foundFiles.length > 0) {
          this.detectedProjects.push({
            language,
            path: dirPath,
            configFiles: foundFiles,
            commands: config.commands,
            check: config.check
          });
        }
      }
      
      // 递归扫描子目录
      for (const item of items) {
        const itemPath = path.join(dirPath, item);
        if (fs.statSync(itemPath).isDirectory() && 
            !item.startsWith('.') && 
            !['node_modules', 'vendor', 'target', 'build', 'dist'].includes(item)) {
          await this.scanDirectory(itemPath, currentDepth + 1, maxDepth);
        }
      }
    } catch (error) {
      console.log(chalk.red(`❌ 扫描目录失败: ${dirPath} - ${error.message}`));
    }
  }

  /**
   * 检查运行环境
   * @param {string} checkCommand - 检查命令
   */
  checkEnvironment(checkCommand) {
    try {
      execSync(checkCommand, { stdio: 'pipe' });
      return true;
    } catch (error) {
      return false;
    }
  }

  /**
   * 执行安装命令
   * @param {Object} project - 项目信息
   */
  async installDependencies(project) {
    console.log(chalk.blue(`\n📦 开始安装 ${project.language} 依赖...`));
    console.log(chalk.gray(`项目路径: ${project.path}`));
    
    // 检查运行环境
    if (!this.checkEnvironment(project.check)) {
      const result = {
        language: project.language,
        path: project.path,
        status: 'failed',
        error: `${project.language} 运行环境未安装`
      };
      this.installResults.push(result);
      console.log(chalk.red(`❌ ${result.error}`));
      return result;
    }
    
    const originalCwd = process.cwd();
    
    try {
      // 切换到项目目录
      process.chdir(project.path);
      
      // 尝试执行安装命令
      for (const command of project.commands) {
        try {
          console.log(chalk.yellow(`⚡ 执行: ${command}`));
          
          // 修改为直接执行npm install，避免递归调用
          const actualCommand = command === 'npm install' ? 'npm install --no-optional --prefer-offline --silent' : command;
          
          const output = execSync(actualCommand, { 
            stdio: 'pipe',
            encoding: 'utf8',
            timeout: 120000, // 减少到2分钟超时
            killSignal: 'SIGKILL' // 强制杀死信号
          });
          
          const result = {
            language: project.language,
            path: project.path,
            status: 'success',
            command: actualCommand,
            output: output.slice(0, 500) // 限制输出长度
          };
          
          this.installResults.push(result);
          console.log(chalk.green(`✅ ${project.language} 依赖安装成功`));
          return result;
          
        } catch (cmdError) {
          console.log(chalk.yellow(`⚠️  命令失败: ${command}`));
          console.log(chalk.gray(`错误: ${cmdError.message.slice(0, 200)}`));
          continue; // 尝试下一个命令
        }
      }
      
      // 所有命令都失败
      const result = {
        language: project.language,
        path: project.path,
        status: 'failed',
        error: '所有安装命令都失败'
      };
      this.installResults.push(result);
      console.log(chalk.red(`❌ ${project.language} 依赖安装失败`));
      return result;
      
    } catch (error) {
      const result = {
        language: project.language,
        path: project.path,
        status: 'failed',
        error: error.message
      };
      this.installResults.push(result);
      console.log(chalk.red(`❌ 安装过程出错: ${error.message}`));
      return result;
    } finally {
      // 恢复原始工作目录
      process.chdir(originalCwd);
    }
  }

  /**
   * 生成安装报告
   */
  generateReport() {
    console.log(chalk.blue('\n📊 安装报告'));
    console.log(chalk.blue('='.repeat(50)));
    
    const successful = this.installResults.filter(r => r.status === 'success');
    const failed = this.installResults.filter(r => r.status === 'failed');
    
    console.log(chalk.green(`✅ 成功: ${successful.length} 个项目`));
    successful.forEach(result => {
      console.log(chalk.green(`  • ${result.language} (${result.path})`));
    });
    
    if (failed.length > 0) {
      console.log(chalk.red(`\n❌ 失败: ${failed.length} 个项目`));
      failed.forEach(result => {
        console.log(chalk.red(`  • ${result.language} (${result.path})`));
        console.log(chalk.gray(`    错误: ${result.error}`));
      });
    }
    
    console.log(chalk.blue('\n🎯 总结'));
    console.log(`检测到项目: ${this.detectedProjects.length}`);
    console.log(`安装成功: ${successful.length}`);
    console.log(`安装失败: ${failed.length}`);
    console.log(`成功率: ${((successful.length / this.installResults.length) * 100).toFixed(1)}%`);
    
    // 保存报告到文件
    const reportData = {
      timestamp: new Date().toISOString(),
      detected: this.detectedProjects.length,
      successful: successful.length,
      failed: failed.length,
      results: this.installResults
    };
    
    fs.writeFileSync(
      path.join(__dirname, 'install-report.json'),
      JSON.stringify(reportData, null, 2)
    );
    
    console.log(chalk.gray(`\n📄 详细报告已保存到: install-report.json`));
  }

  /**
   * 主执行函数
   */
  async run() {
    console.log(chalk.bold.blue('🚀 Builder.Alyr.Net 智能体代码规范检测工具 智能多语言依赖自动安装器'));
    console.log(chalk.blue('='.repeat(50)));
    console.log(chalk.gray('支持语言: Node.js, Python, Java, Go, Rust, PHP, Ruby, C#, Flutter, Swift'));
    console.log(chalk.gray('版本: V4.2.3 | © 2020-2025 ALYR.NET\n'));
    
    try {
      // 1. 扫描项目
      const hasProjects = await this.scanProject();
      if (!hasProjects) {
        return;
      }
      
      // 2. 安装依赖
      console.log(chalk.blue('\n🔧 开始安装依赖...'));
      for (const project of this.detectedProjects) {
        await this.installDependencies(project);
      }
      
      // 3. 生成报告
      this.generateReport();
      
      console.log(chalk.green('\n🎉 智能安装完成！'));
      
      // 确保程序正常退出
      setTimeout(() => {
        process.exit(0);
      }, 1000);
      
    } catch (error) {
      console.error(chalk.red(`\n💥 安装过程出错: ${error.message}`));
      process.exit(1);
    }
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const installer = new SmartInstaller();
  installer.run().catch(console.error);
}

module.exports = SmartInstaller;